package com.xaicode.learn.java.thread;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * delay queue
 *
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
public class QueueDelay {

    public static void main(String[] args) throws InterruptedException {
        final DelayQueue<Student> dq = new DelayQueue<>();
        for (int i = 0; i < 5; i++) {
            Student student = new Student("学生" + i, Math.round(Math.random() * 10 + i));
            dq.put(student);
        }

        //System.out.println("dq.peek() " + dq.peek().getName());
        System.out.println("dq.poll() " + dq.poll(1,TimeUnit.SECONDS).getName());
    }

    public static class Student implements Delayed {

        private String name;
        private long submitTime;
        private long workTime;

        private String getName() {
            return this.name + " 交卷，用时 " + this.workTime;
        }

        public Student(String name, long submitTime) {
            this.name = name;
            this.workTime = submitTime;
            this.submitTime = TimeUnit.NANOSECONDS.convert(submitTime, TimeUnit.MILLISECONDS) + System.nanoTime();
            System.out.println(this.name + " 交卷，用时 " + this.workTime);
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(submitTime - System.nanoTime(), TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            Student that = (Student) o;
            return submitTime > this.submitTime ?
                    1 :
                    (submitTime < that.submitTime ? -1 : 0);
        }
    }


}
